<template>
  <div>
    <jc-bar :prve-btn="true" :search-btn="false" @prve="handleBack">
      <template><v-spacer></v-spacer></template>
    </jc-bar>
    <v-main class="d-flex justify-center">
      <v-container style="display: flex; flex-direction: column; row-gap: 20px">
        <v-card style="width: 100%; flex: 1; height: calc(100% - 120px); overflow: auto">
          <v-list class="w-full">
            <v-list-item-group v-model="model">
              <v-list-item v-for="(item, i) in items" :key="i" @click="handleTag(i)">
                <v-list-item-content>
                  <v-list-item-title v-text="item.content"> </v-list-item-title>
                  <v-list-item-subtitle v-text="item.timestamp"></v-list-item-subtitle>
                </v-list-item-content>

                <v-list-item-action>
                  <v-btn icon @click.stop="handleTag(i)">
                    <v-icon>打TAG</v-icon>
                  </v-btn>
                </v-list-item-action>
                <v-list-item-action>
                  <v-btn icon @click.stop="openEdit(i)">
                    <j-icon color="#9E9E9E" size="20">mdi-book-edit-outline</j-icon>
                  </v-btn>
                </v-list-item-action>
              </v-list-item>
            </v-list-item-group>
          </v-list>
        </v-card>
        <v-divider></v-divider>
        <v-card elevation="6" style="position: sticky; bottom: 10px; left: 0; right: 0">
          <v-card-actions>
            <v-btn text @click="play">{{ btnText }}</v-btn>
            <v-btn text @click="audioBack">后退500毫秒</v-btn>
            <v-btn text @click="audioNext">前进500毫秒</v-btn>
            <v-btn text @click="openLyricInfo">歌曲信息</v-btn>
          </v-card-actions>
          <v-card-text>
            <v-progress-linear :value="pro"></v-progress-linear>
          </v-card-text>
          <v-card-text v-if="testCurrentLyric.content">
            {{ testCurrentLyric.content }}
          </v-card-text>
          <v-card-text>{{ currentTime }}</v-card-text>
          <v-card-actions>
            <v-btn text @click="exportLyric">导出歌词</v-btn>
            <v-btn text @click="submit" v-if="!isUpper">提交歌词</v-btn>

            <v-btn text @click="handleTest">测试</v-btn>
            <v-btn text @click="bisuDialog = true">倍速设置</v-btn>
            <v-btn text color="success" @click="passShow = true" v-if="lyricId != null && !isUpper">审核</v-btn>
          </v-card-actions>
          <v-card-text v-if="lyricList.length > 0"> 当前已经有人贡献了{{ lyricList.length }}次歌词 </v-card-text>
          <v-card-actions>
            <v-btn
              v-for="(l, index) in lyricList"
              :key="l.id"
              :color="`${l.id == lyricId ? 'success' : ''}`"
              @click="handleEdit(l)"
              >修改歌词{{ l.id }}</v-btn
            >
          </v-card-actions>
        </v-card>
      </v-container>
    </v-main>
    <v-dialog v-model="dialog" width="500">
      <v-card>
        <v-card-title class="text-h5 grey lighten-2"> 编辑歌词 </v-card-title>
        <v-card-text>
          <textarea style="margin: 10px" ref="textarea" :rows="20" v-model="textLyric" cols="36"></textarea>
        </v-card-text>
        <v-divider></v-divider>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="primary" text @click="dialog = false"> 关闭 </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <v-dialog v-model="lyricDialog" width="500">
      <v-card>
        <v-card-title class="text-h5 grey lighten-2"> 歌曲信息 </v-card-title>
        <v-card-text>
          <template>
            <v-form ref="form">
              <v-text-field v-model="lyricInfo.ar" label="歌曲演唱者"></v-text-field>

              <v-text-field v-model="lyricInfo.au" label="歌曲创作人"></v-text-field>
            </v-form>
          </template>
        </v-card-text>
        <v-divider></v-divider>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="primary" text @click="lyricDialog = false"> 关闭 </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <v-dialog v-model="bisuDialog" width="500">
      <v-card>
        <v-card-title class="text-h5 grey lighten-2"> 倍速设置 </v-card-title>
        <v-card-actions>
          <v-radio-group v-model="bisuValue" row @change="handleSetPlaybackRate">
            <v-radio label="1倍速" :value="1"></v-radio>
            <v-radio label="1.5倍速" :value="1.5"></v-radio>
            <v-radio label="2倍速" :value="2"></v-radio>
          </v-radio-group>
        </v-card-actions>
        <v-divider></v-divider>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="primary" text @click="bisuDialog = false"> 关闭 </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- 审核通过 -->
    <v-dialog v-model="passShow" width="500">
      <v-card>
        <v-card-title class="text-h5 grey lighten-2"> 确定通过？ </v-card-title>
        <v-divider></v-divider>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="success" text @click="pass">确定</v-btn>
          <v-btn color="primary" text @click="passShow = false"> 关闭 </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

<script>
import { mapActions } from "vuex";
import { Lrc, Runner } from "lrc-kit";
import JcBar from "../../layout/JcBar";
import { addLyric, listLyric, updateLyric } from "../../api/lyric";

export default {
  name: "MakeLyric",
  props: {
    id: {
      // 歌曲ID号
      type: String,
      required: true,
    },
  },
  components: {
    JcBar,
  },
  computed: {
    isUpper() {
      return this.lyricList.some((item) => item.isUpper == 1);
    },
    textLyric: {
      get() {
        return this.items.map((item) => item.content).join("\n");
      },
      set(text) {
        this.items = text.split("\n").map((item, index) => ({
          content: item,
          timestamp: this.items[index] ? this.items[index].timestamp : 0,
        }));
      },
    },
  },
  data() {
    return {
      passShow: false,
      lyricId: null,
      bisuDialog: false,
      bisuValue: 1,
      lyricDialog: false,
      dialog: false,
      items: [],
      model: 1,
      lrc: null,
      audio: null,
      btnText: "播放",
      pro: 0,
      sgbData: null,
      testCurrentLyric: {
        content: "",
        timestamp: "",
      },
      lyricInfo: {
        // 歌曲演唱者
        ar: "",
        // 歌曲所属专辑名称
        al: "",
        // 歌曲名称
        ti: "",
        // 歌曲创作人
        au: "",
        // 歌曲长度，例如 2:50
        length: "",
        // LRC 文件的创建者
        by: "",
        // 时间戳整体调整，单位为毫秒，+ 表示时间向上偏移，- 表示时间向下偏移
        offset: "",
        // 创建 LRC 文件的播放器或编辑器
        re: "",
        // 程序版本号
        ve: "",
      },
      lyricList: [],
      currentTime: 0,
    };
  },

  mounted() {
    this.init();
  },
  destroyed() {
    console.log("网页销毁时");
    this.audio.pause();
    this.audio = null;
  },
  // activated() {
  //   this.init();
  // },
  methods: {
    ...mapActions({
      getItem: "sgb/getItem",
    }),
    // 退出上一页
    handleBack() {
      this.$router.back();
    },
    init() {
      this.lrc = new Lrc();
      listLyric({ zanmeiId: this.id })
        .then((res) => {
          console.log("获取列表", res);
          if (res.code == 200) {
            this.lyricList = res.rows;
          }
        })
        .catch((err) => {
          console.log("获取错误", err);
        });

      this.getItem(this.id).then((res) => {
        this.items = res.lyric.split("\n").map((item) => ({ content: item, timestamp: "" }));
        this.lyricInfo.al = res.shijiName;
        this.lyricInfo.ti = res.mulu;

        this.sgbData = res;
        if (!this.audio) {
          this.audio = new Audio();
        }
        this.handleSetPlaybackRate();

        this.audio.src = res.dmtUrl.adUrl;
        this.audio.addEventListener("play", () => {
          this.btnText = "暂停";
        });
        this.audio.addEventListener("pause", () => {
          this.btnText = "播放";
        });
        this.audio.addEventListener("timeupdate", () => {
          const { currentTime } = this.audio;
          const { duration } = this.audio;
          this.pro = (currentTime / duration) * 100;
          this.currentTime = currentTime;
        });
        this.audio.addEventListener("ended", () => {
          this.testCurrentLyric = {};
          this.pro = 0;
        });
        this.audio.addEventListener("canplaythrough", () => {
          this.lyricInfo.length = this.audio.duration;
        });
      });
    },
    play() {
      if (this.audio.paused) {
        this.audio.play();
      } else {
        this.audio.pause();
      }
    },
    audioBack() {
      if (this.audio.currentTime >= 0.5) {
        this.audio.currentTime = this.audio.currentTime - 0.5;
        return;
      }
      this.audio.currentTime = 0;
    },
    audioNext() {
      this.audio.currentTime = this.audio.currentTime += 0.5;
    },
    handleTag(index = null) {
      if (index != null) {
        this.items[index].timestamp = this.audio.currentTime;
      } else {
        this.items[this.model].timestamp = this.audio.currentTime;
      }
      if (this.items.length - 1 > this.model) {
        this.model += 1;
      }
    },
    lyric() {
      this.lrc.lyrics = this.items;
      this.lrc.info = this.lyricInfo;
      console.log(this.lrc.toString());
      return this.lrc.toString();
    },
    exportLyric() {
      // 创建一个文本字符串
      const text = this.lyric();
      // 创建一个Blob对象
      const blob = new Blob([text], { type: "text/plain;charset=utf-8" });
      // 创建一个a标签
      const a = document.createElement("a");
      // 设置a标签的href属性为Blob URL
      a.href = URL.createObjectURL(blob);
      // 设置a标签的下载属性为文件名
      a.download = `${this.sgbData.mulu}.lrc`;
      // 模拟点击a标签进行下载
      a.click();
    },
    async submit() {
      try {
        const res = await addLyric({
          lyric: this.lyric(),
          zanmeiId: this.id,
          isUpper: 0,
        });
        if (res.code === 500) {
          // eslint-disable-next-line no-alert
          alert("服务器异常");
          return;
        }
        // eslint-disable-next-line no-alert
        alert("提交成功");
        this.init();
      } catch (err) {
        console.log("提交失败：", err);
        alert("提交失败");
      }
    },
    async pass() {
      try {
        await addLyric({
          lyric: this.lyric(),
          zanmeiId: this.id,
          isUpper: 1,
        });
        this.init();
        this.passShow = false;
        alert("提交成功");
      } catch (err) {
        console.log("提交失败：", err);
        alert("提交失败");
      }
    },
    openEdit(row) {
      this.dialog = true;
      setTimeout(() => {
        this.$refs.textarea.focus();
        const startLine = this.items
          .filter((item, index) => index < row)
          .map((item) => item.content)
          .join(",");
        this.$refs.textarea.selectionStart = startLine.length + 1;
        this.$refs.textarea.selectionEnd = startLine.length + 1 + this.items[row].content.length + 1;
      }, 500);
    },
    handleTest() {
      this.play();
      this.audio.removeEventListener("timeupdate", this.runLyric.bind(this));
      this.audio.addEventListener("timeupdate", this.runLyric.bind(this));
    },
    runLyric() {
      const l = Lrc.parse(this.lyric());
      const runner = new Runner(l);
      runner.timeUpdate(this.audio.currentTime);
      const lyric = runner.curLyric();
      this.testCurrentLyric = lyric;
    },
    openLyricInfo() {
      this.lyricDialog = true;
    },
    handleEdit(lyric) {
      this.lyricId = lyric.id;
      const l = Lrc.parse(lyric.lyric);
      this.items = l.lyrics.sort((a, b) => a.timestamp - b.timestamp);
      this.lyricInfo = l.info;
    },
    handleSetPlaybackRate() {
      this.audio.playbackRate = this.bisuValue;
    },
  },

  watch: {
    id() {
      this.init();
    },
  },
};
</script>

<style scoped lang="scss"></style>
